import Header from '@/components/common/Header.vue';
import RecruitModal from '@/components/common/RecruitModal.vue';
import OrderSuccessModal from '@/components/common/OrderSuccessModal.vue';
import OrderModifyModal from '@/components/common/OrderModifyModal.js';

import { request, getFullImageUrl, initBaseUrl } from '../../../utils/request';
import { ORDER_STATUS, JOB_STATUS } from '../../../utils/status';
import { getLocation } from '../../../utils/mapUtils';

// 这两个函数在原始代码中被引用但没有导入，需要添加
function getJobStatusText(status) {
  const statusMap = {
    [JOB_STATUS.PENDING]: '待接单',
    [JOB_STATUS.ACCEPTED]: '已接单',
    [JOB_STATUS.IN_PROGRESS]: '进行中',
    [JOB_STATUS.COMPLETED]: '已完成',
    [JOB_STATUS.CANCELED]: '已取消'
  };
  return statusMap[status] || '未知状态';
}

function getOrderStatusText(status) {
  const statusMap = {
    [ORDER_STATUS.ACCEPTED]: '已接单',
    [ORDER_STATUS.IN_PROGRESS]: '进行中',
    [ORDER_STATUS.COMPLETED]: '已完成',
    [ORDER_STATUS.CANCELED]: '已取消'
  };
  return statusMap[status] || '未知状态';
}

export default {
    components: {
        Header,
        RecruitModal,
        OrderSuccessModal,
        OrderModifyModal
    },
    data() {
        return {
            headerData: {
                title: '订单中心',
                subtitle: ''
            },
            currentMainTab: 'receive',
            currentTab: 'all',
            orders: [],
            page: 1,
            limit: 10,
            total: 0,
            startX: 0,
            moveX: 0,
            slideWidth: 0,
            isDragging: false,
            statusMap: {
                'all': '',
                'accepted': ORDER_STATUS.ACCEPTED,
                'inProgress': ORDER_STATUS.IN_PROGRESS,
                'completed': ORDER_STATUS.COMPLETED,
                'cancelled': ORDER_STATUS.CANCELED,
            },
            publishStatusMap: {
                'all': '',
                'pending': JOB_STATUS.PENDING,
                'accepted': JOB_STATUS.ACCEPTED,
                'inProgress': JOB_STATUS.IN_PROGRESS,
                'completed': JOB_STATUS.COMPLETED,
                'cancelled': JOB_STATUS.CANCELED
            },
            showRecruitModal: false,
            selectedOrder: null,
            showSuccessModal: false,
            successOrderData: {},
            slideTimers: {}, // 用于管理滑动定时器
            showModifyModal: false,
            currentModifyOrderId: null
        };
    },
    onLoad() {
        this.fetchOrders();
        initBaseUrl();
    },
    onReady() {
        this.$nextTick(() => {
            this.orders.forEach(order => {
                if (this.isValidOrder(order) && order.status === 2) {
                    this.calculateAreaWidth(order);
                }
            });
        });
    },
    methods: {
        getFullImageUrl,

        // 新增：订单有效性检查的通用方法
        isValidOrder(order) {
            if (!order) {
                console.error('Invalid order: order is undefined or null');
                return false;
            }

            // 检查是否有有效的订单标识
            if (!order.order_id && !order.task_id) {
                console.error('Invalid order: missing both order_id and task_id', order);
                return false;
            }

            return true;
        },

        gotoNavigation(order) {
            if (!this.isValidOrder(order)) {
                uni.showToast({
                    title: '订单信息无效',
                    icon: 'none'
                });
                return;
            }

            uni.openLocation({
                latitude: parseFloat(order.latitude) || 0,
                longitude: parseFloat(order.longitude) || 0,
                name: '目的地',
                address: order.address || '',
                success: () => {
                    console.log('导航已打开');
                },
                fail: (err) => {
                    console.error('打开导航失败', err);
                    uni.showToast({
                        title: '无法打开导航',
                        icon: 'none'
                    });
                }
            });
        },

        switchMainTab(tab) {
            this.currentMainTab = tab;
            this.currentTab = 'all';
            this.page = 1;
            this.orders = [];
            this.total = 0;
            this.fetchOrders();
        },

        switchTab(tab) {
            this.currentTab = tab;
            this.page = 1;
            this.orders = [];
            this.total = 0;
            this.fetchOrders();
        },

        async fetchOrders(isLoadMore = false) {
            try {
                const location = await getLocation();
                const url = this.currentMainTab === 'receive'
                    ? '/Workerorders/order_list'
                    : '/WorkerPosts/my_posts';

                const statusMap = this.currentMainTab === 'my_posts'
                    ? this.publishStatusMap
                    : this.statusMap;
                const status = statusMap[this.currentTab] || '';

                const params = {
                    page: this.page,
                    limit: this.limit
                };

                if (status) {
                    params.status = status;
                }

                if (location) {
                    params.latitude = location.latitude;
                    params.longitude = location.longitude;
                }

                request({
                    url: url,
                    method: 'GET',
                    data: params
                }).then(res => {
                    console.log('订单数据:', res);
                    if (res.code === 200 && Array.isArray(res.data)) {
                        // 严格过滤并处理订单数据
                        const newOrders = res.data
                            .filter(order => this.isValidOrder(order) && order.status !== 0) // 过滤掉已报名状态(0)的订单
                            .map(order => {
                                // 确保order_id始终存在
                                order.order_id = order.order_id || order.task_id;

                                if (order.status === 2) {
                                    return {
                                        ...order,
                                        thumbX: 0,
                                        areaWidth: 0,
                                        thumbWidth: 80,
                                        isDisabled: false,
                                        maxX: 0 // 新增maxX属性
                                    };
                                }
                                return order;
                            });
                        
                        if (isLoadMore) {
                            // 加载更多模式，追加数据
                            this.orders = [...this.orders, ...newOrders];
                        } else {
                            // 刷新模式，重置数据
                            this.orders = newOrders;
                        }
                        
                        this.total = res.total || 0;
                        
                        // 停止下拉刷新
                        uni.stopPullDownRefresh();
                    } else {
                        console.error('获取订单数据格式错误:', res);
                        if (!isLoadMore) {
                            this.orders = [];
                        }
                        this.total = 0;
                        uni.stopPullDownRefresh();
                    }
                });
            } catch (error) {
                console.error('获取位置信息失败:', error);
                this.fetchOrdersWithoutLocation(isLoadMore);
            }
        },

        // 加载更多订单
        // 生命周期钩子
        loadMoreOrders() {
            if (this.orders.length >= this.total && this.total > 0) {
                // 已经加载完所有数据
                return;
            }
            
            this.page++;
            this.fetchOrders(true);
        },

        // 下拉刷新
        onPullDownRefresh() {
            this.page = 1;
            this.fetchOrders();
        },

        // 上拉加载更多
        onReachBottom() {
            this.loadMoreOrders();
        },

        fetchOrdersWithoutLocation(isLoadMore = false) {
            const url = this.currentMainTab === 'receive'
                ? '/Workerorders/order_list'
                : '/WorkerPosts/my_posts';

            const statusMap = this.currentMainTab === 'my_posts'
                ? this.publishStatusMap
                : this.statusMap;
            const status = statusMap[this.currentTab] || '';

            const params = {
                page: this.page,
                limit: this.limit
            };

            if (status) {
                params.status = status;
            }

            request({
                url: url,
                method: 'GET',
                data: params
            }).then(res => {
                console.log('无位置信息获取订单:', res);
                if (res.code === 200 && Array.isArray(res.data)) {
                    const newOrders = res.data
                        .filter(order => this.isValidOrder(order) && order.status !== 0) // 过滤掉已报名状态(0)的订单
                        .map(order => {
                            order.order_id = order.order_id || order.task_id;

                            if (order.status === 2) {
                                return {
                                    ...order,
                                    thumbX: 0,
                                    areaWidth: 0,
                                    thumbWidth: 80,
                                    isDisabled: false,
                                    maxX: 0 // 新增maxX属性
                                };
                            }
                            return order;
                        });
                    
                    if (isLoadMore) {
                        // 加载更多模式，追加数据
                        this.orders = [...this.orders, ...newOrders];
                    } else {
                        // 刷新模式，重置数据
                        this.orders = newOrders;
                    }
                    
                    this.total = res.total || 0;
                    this.$nextTick(() => {
                        this.orders.forEach(order => {
                            if (order.status === 2) {
                                this.calculateAreaWidth(order);
                            }
                        });
                    });
                    
                    uni.stopPullDownRefresh();
                } else {
                    if (!isLoadMore) {
                        this.orders = [];
                    }
                    this.total = 0;
                    uni.stopPullDownRefresh();
                }
            });
        },

        calculateAreaWidth(order) {
            if (!this.isValidOrder(order)) return;

            const query = uni.createSelectorQuery().in(this);
            query.select(`.slide-btn__area-${order.order_id}`).boundingClientRect(res => {
                if (res) {
                    const index = this.orders.findIndex(item => item.order_id === order.order_id);
                    if (index !== -1) {
                        this.$set(this.orders[index], 'areaWidth', res.width);
                        // 当计算出areaWidth后，更新maxX
                        this.$set(this.orders[index], 'maxX', res.width - order.thumbWidth);
                    }
                }
            }).exec();
        },
        
        // 弹窗相关方法
        closeRecruitModal() {
            this.showRecruitModal = false;
            this.selectedOrder = null;
        },
        
        closeSuccessModal() {
            this.showSuccessModal = false;
            this.successOrderData = {};
        },
        
        // 处理订单成功事件
        handleOrderSuccess(orderData) {
            this.successOrderData = orderData;
            this.showSuccessModal = true;
            
            // 刷新订单列表
            this.fetchOrders();
        },

        onSlide(e, order) {
            // 更严格的参数检查
            if (!order || typeof order !== 'object') {
                console.error('Invalid order parameter:', order);
                uni.showToast({
                    title: '订单信息无效',
                    icon: 'none'
                });
                return;
            }

            // 双重检查order是否有效
            if (!this.isValidOrder(order)) {
                uni.showToast({
                    title: '订单信息无效',
                    icon: 'none'
                });
                return;
            }

            const currentX = e.detail.x;
            const source = e.detail.source;
            const index = this.orders.findIndex(item =>
                item.order_id === order.order_id
            );

            if (index === -1) {
                console.error('订单不在列表中', order);
                return;
            }

            const currentOrder = this.orders[index];
            if (!currentOrder) {
                console.error('当前订单不存在', index);
                return;
            }

            // 如果已经提交过，不再处理
            if (currentOrder.isSubmitting) {
                return;
            }

            if (!currentOrder.areaWidth || currentOrder.areaWidth === 0) {
                this.calculateAreaWidth(currentOrder);
                return;
            }

            // 只有当source为'touch'时才处理，避免程序触发的change事件
            if (source === 'touch') {
                if (currentX >= currentOrder.areaWidth - currentOrder.thumbWidth) {
                    this.$set(this.orders[index], 'isDisabled', true);
                    this.$set(this.orders[index], 'thumbX', currentOrder.areaWidth - currentOrder.thumbWidth);
                    this.$set(this.orders[index], 'isSubmitting', true);

                    const orderId = currentOrder.order_id;
                    if (orderId) {
                        setTimeout(() => {
                            this.completeOrder(orderId, index);
                        }, 500);
                    } else {
                        console.error('订单ID不存在', currentOrder);
                        this.$set(this.orders[index], 'isSubmitting', false);
                        uni.showToast({
                            title: '无法完成订单，缺少订单ID',
                            icon: 'none'
                        });
                    }
                } else {
                    // 滑动过程中更新位置
                    this.$set(this.orders[index], 'thumbX', currentX);
                    
                    // 当用户松开手指时（source为touch且x不再变化），检查是否需要回退
                    // 使用setTimeout来检测滑动结束
                    clearTimeout(this.slideTimers[order.order_id]);
                    this.slideTimers[order.order_id] = setTimeout(() => {
                        const finalX = this.orders[index].thumbX;
                        const threshold = currentOrder.areaWidth - currentOrder.thumbWidth;
                        if (finalX < threshold) {
                            this.$set(this.orders[index], 'thumbX', 0);
                        }
                    }, 100);
                }
            }
        },



        completeOrder(orderId, index) {
            request({
                url: `Workerorders/completeOrder`,
                method: 'POST',
                data: {
                    order_id: orderId
                }
            }).then(res => {
                // 无论成功失败，都重置提交标志
                if (index !== -1 && index < this.orders.length) {
                    this.$set(this.orders[index], 'isSubmitting', false);
                }

                if (res.code === 200) {
                    if (index !== -1 && index < this.orders.length) {
                        this.$delete(this.orders, index);
                    }

                    uni.showToast({
                        title: '订单已完成',
                        icon: 'success'
                    });
                    setTimeout(() => {
                        this.fetchOrders();
                    }, 500);
                } else {
                    console.error('completeOrder failed:', res);
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                    if (index !== -1 && index < this.orders.length) {
                        this.$set(this.orders[index], 'isDisabled', false);
                        this.$set(this.orders[index], 'thumbX', 0);
                    }
                }
            }).catch(err => {
                console.error('completeOrder error:', err);
                // 网络错误也要重置提交标志
                if (index !== -1 && index < this.orders.length) {
                    this.$set(this.orders[index], 'isSubmitting', false);
                }
                uni.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
                if (index !== -1 && index < this.orders.length) {
                    this.$set(this.orders[index], 'isDisabled', false);
                    this.$set(this.orders[index], 'thumbX', 0);
                }
            });
        },

        getStatusClass(status) {
            if (this.currentMainTab === 'my_posts') {
                switch (status) {
                    case JOB_STATUS.ACCEPTED: return 'accepted';
                    case JOB_STATUS.IN_PROGRESS: return 'inProgress';
                    case JOB_STATUS.COMPLETED: return 'completed';
                    case JOB_STATUS.CANCELED: return 'cancelled';
                    case JOB_STATUS.PENDING: return 'pending';
                    default: return 'unknown';
                }
            }
            switch (status) {
                case ORDER_STATUS.ACCEPTED: return 'accepted';
                case ORDER_STATUS.IN_PROGRESS: return 'inProgress';
                case ORDER_STATUS.COMPLETED: return 'completed';
                case ORDER_STATUS.CANCELED: return 'cancelled';
                default: return 'unknown';
            }
        },

        getStatusText(status) {
            if (this.currentMainTab === 'my_posts') {
                return getJobStatusText(status);
            } else {
                return getOrderStatusText(status);
            }
        },
        selectFriend(order) {
            this.selectedOrder = order;
            this.showRecruitModal = true;
        },
        gotoChat(item) {
            if (!this.isValidOrder(item)) {
                uni.showToast({
                    title: '订单信息无效',
                    icon: 'none'
                });
                return;
            }

            if (this.currentMainTab == 'my_posts') {
                uni.switchTab({
                    url: `/pages/chat/index`
                });
                return;
            }

            const requiredFields = ['status_image', 'session_id'];
            const taskId = item.task_id; // 已经通过isValidOrder确保有值
            const missingRequiredFields = requiredFields.filter(field => !item[field]);

            if (missingRequiredFields.length > 0) {
                console.error(`缺少必要字段: ${missingRequiredFields.join(', ')}`, item);
                uni.showToast({
                    title: '无法进入聊天，订单信息不完整',
                    icon: 'none'
                });
                return;
            }

            const otherUserId = item.other_user_id || '';
            const otherUserName = item.employer_name || '未知用户';
            const otherAvatar = item.employer_avatar || '/static/image/logo.jpg';

            uni.navigateTo({
                url: `/pages/chat/chat-detail?statusImage=${getFullImageUrl(item.status_image)}&jobId=${taskId}&session_id=${item.session_id}&otherUserId=${otherUserId}&otherUserName=${encodeURIComponent(otherUserName)}&otherAvatar=${otherAvatar}`
            });
        },

        modifyOrder(order) {
            if (!this.isValidOrder(order)) {
                uni.showToast({
                    title: '订单信息无效',
                    icon: 'none'
                });
                return;
            }

            // 显示修改订单模态框
            const orderId = order.order_id || order.task_id;
            this.currentModifyOrderId = orderId;
            this.showModifyModal = true;
        },

        // 处理订单修改成功事件
        handleModifySuccess() {
            this.showModifyModal = false;
            // 刷新订单列表
            this.fetchOrders();
        },
        
        // 取消订单方法
        cancelOrder(orderId) {
            if (!orderId) {
                console.error('取消订单失败：缺少订单ID');
                uni.showToast({
                    title: '取消订单失败',
                    icon: 'none'
                });
                return;
            }

            // 显示确认对话框
            uni.showModal({
                title: '取消订单',
                content: '确定要取消此订单吗？',
                success: (res) => {
                    if (res.confirm) {
                        // 用户确认取消
                        request({
                            url: `Workerorders/cancelOrder`,
                            method: 'POST',
                            data: {
                                order_id: orderId
                            }
                        }).then(res => {
                            if (res.code === 200) {
                                uni.showToast({
                                    title: '订单已取消',
                                    icon: 'success'
                                });
                                // 刷新订单列表
                                setTimeout(() => {
                                    this.fetchOrders();
                                }, 500);
                            } else {
                                console.error('取消订单失败:', res);
                                uni.showToast({
                                    title: res.msg || '取消订单失败',
                                    icon: 'none'
                                });
                            }
                        }).catch(err => {
                            console.error('取消订单网络错误:', err);
                            uni.showToast({
                                title: '网络错误，请重试',
                                icon: 'none'
                            });
                        });
                    }
                }
            });
        },
        onUnload() {
            // 清理所有滑动定时器
            Object.keys(this.slideTimers).forEach(key => {
                if (this.slideTimers[key]) {
                    clearTimeout(this.slideTimers[key]);
                    delete this.slideTimers[key];
                }
            });
        },
        onHide() {
            // 页面隐藏时也清理定时器
            Object.keys(this.slideTimers).forEach(key => {
                if (this.slideTimers[key]) {
                    clearTimeout(this.slideTimers[key]);
                    delete this.slideTimers[key];
                }
            });
        },
        
        // 去评论方法，传递评论页面所需的完整参数
        gotoComment(order) {
            if (!this.isValidOrder(order)) {
                uni.showToast({
                    title: '订单信息无效',
                    icon: 'none'
                });
                return;
            }
            console.log("去评论订单",order)

            const orderId = order.order_id || order.task_id;
            const employerAvatar = order.employer_avatar || '';
            const employerName = order.employer_name || '未知用户';
            
            // 导航到评论页面，传递评论所需的完整信息
            uni.navigateTo({
                url: `/pages/pageMy/orderCenter/comment?order_id=${orderId}&employer_avatar=${encodeURIComponent(employerAvatar)}&employer_name=${encodeURIComponent(employerName)}`
            });
        },
        goBack() {
            uni.navigateBack({
                delta: 1
            });
        },
        
        // 测试订单成功弹窗
        testOrderSuccessModal() {
            console.log('测试订单成功弹窗');
            // 设置模拟的订单数据
            this.successOrderData = {
                job_title: '测试订单',
                job_address: '测试地址',
                job_time: '2023-10-01 10:00-12:00',
                salary: '100',
                contact_name: '测试联系人',
                contact_phone: '13800138000',
                latitude: 39.9087,
                longitude: 116.3975
            };
            // 显示弹窗
            this.showSuccessModal = true;
            
            // 记录日志以便调试
            console.log('订单数据:', this.successOrderData);
            console.log('弹窗显示状态:', this.showSuccessModal);
        }
    }
};
